package com.wkbb.basic.controller.manage;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.model.Employee;
import com.wkbb.basic.model.OrgStructureUser;
import com.wkbb.basic.service.OrgStructureService;
import com.wkbb.basic.service.OrgStructureUserService;
import com.wkbb.basic.service.TeacherManageService;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.EmployeeInfoDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.*;

/**
 * @author lizhichao
 * @date 2019/8/9
 * @description
 */
@RestController
@Api(description = "退休老师管理")
@RequestMapping("/basic/{apiVersion}/retiredTeacher/manage")
@Slf4j
public class RetiredTeachersManageController extends BaseController {

    @Autowired
    private TeacherManageService teacherManageService;
    @Autowired
    private OrgStructureUserService orgStructureUserService;

    @ApiOperation("新增退休老师")
    @RequestMapping(value = "/addRetiredTeachers", method = RequestMethod.POST)
    public ResultDTO addRetiredTeachers(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织架构Id",required = true) @RequestParam(name = "structureId",required = false) Long structureId,
            @RequestBody EmployeeInfoDto employeeInfoDto) {
        log.info("***********RetiredTeachersManageController.addRetiredTeachers******apiVersion:{},structureId:{}", apiVersion, structureId);
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (employeeInfoDto != null && employeeInfoDto.getId() != null && employeeInfoDto.getUserId() != null) {
            try {
                Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
                return orgStructureUserService.addRetiredTeacher(employeeInfoDto,userDto.getName(),structureId,orgId);
            } catch (Exception e) {
                log.error("增加退休老师异常", e);
                return new ResultDTO(false);
            }
        } else {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        }
    }

    @ApiOperation("批量新增退休老师")
    @RequestMapping(value = "/addRetiredTeachersBatch", method = RequestMethod.POST)
    public ResultDTO addRetiredTeachersBatch(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织架构Id",required = true) @RequestParam(name = "structureId",required = false) Long structureId,
            @RequestBody List<EmployeeInfoDto> employeeInfoDtos) {
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (employeeInfoDtos.size() == 0 && employeeInfoDtos.isEmpty()) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        } else {
            try {
                Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
                return orgStructureUserService.addRetiredTeacherBatch(employeeInfoDtos,userDto.getName(),structureId,orgId);
            } catch (Exception var11) {
                log.error("批量增加退休老师异常", var11);
                return new ResultDTO(false);
            }
        }
    }

    @ApiOperation("批量导入退休老师")
    @RequestMapping(value = "/importRetiredTeachersBatch", method = RequestMethod.POST)
    public ResultDTO importRetiredTeachersBatch(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "文件",required = true) @RequestParam(name = "file",required = false) MultipartFile multipartFile) {
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (multipartFile == null) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        } else {
            try {
                Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
                File file = new File(multipartFile.getOriginalFilename());
                List<Object[]> objects = ExcelUtil.importExcel(new FileInputStream(file));
                //退休老师信息数据集合
                List<Employee> employees = new ArrayList();
                //组织成员数据信息集合
                List<OrgStructureUser> orgStructureUserList = new ArrayList();
                //组装老师数据
              for(Object[] obj : objects ){
                  Employee employee = new Employee();
                  employee.setJobNo(obj[0].toString());//学号
                  employee.setCreateBy(userDto.getName());
                  employee.setUpdateBy(userDto.getName());
                  employee.setOrgId(orgId);

                  OrgStructureUser orgStructureUser = new OrgStructureUser();
                  //todo 根据学号查询userId和structureId
//                  orgStructureUser.setUserId(employee.getUserId());
//                  orgStructureUser.setStructureId(structureId);
                  orgStructureUser.setOrgId(orgId);
                  orgStructureUserList.add(orgStructureUser);
              }

              return this.orgStructureUserService.importRetiredTeacherBatch(employees,orgStructureUserList);
            } catch (Exception e) {
                log.error("批量导入退休老师异常", e);
                return new ResultDTO(false);
            }
        }
    }

    @ApiOperation("移动到老师")
    @RequestMapping(value = "/retiredTeachersToEmployee", method = RequestMethod.PUT)
    public ResultDTO retiredTeachersToEmployee(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @RequestBody EmployeeInfoDto employeeInfoDto) {
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (employeeInfoDto != null && employeeInfoDto.getId() != null && employeeInfoDto.getUserId() != null) {
            try {
                return this.orgStructureUserService.retiredTeacherToTeacher(employeeInfoDto,userDto.getName());
            } catch (Exception var6) {
                log.error("移动到职工异常", var6);
                return new ResultDTO(false);
            }
        } else {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        }
    }

    @ApiOperation("批量移动到老师")
    @RequestMapping(value = "/retiredTeachersToEmployeeBatch", method = RequestMethod.PUT)
    public ResultDTO retiredTeachersToEmployeeBatch(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @RequestBody List<EmployeeInfoDto> employeeInfoDtos) {
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (employeeInfoDtos.size() == 0 || employeeInfoDtos.isEmpty()) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        } else {
            try {
            return this.orgStructureUserService.retiredTeacherToTeacherBatch(employeeInfoDtos,userDto.getName());
            } catch (Exception e) {
                log.error("批量移动到职工表异常", e);
                return new ResultDTO(false);
            }
        }
    }

    @ApiOperation("批量删除退休老师")
    @RequestMapping(value = "/deleteRetiredTeachersBatch", method = RequestMethod.DELETE)
    public ResultDTO deleteRetiredTeachersBatch(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam("退休老师集合") @RequestBody List<EmployeeInfoDto> employeeInfoDtos) {
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (employeeInfoDtos.size() == 0 && employeeInfoDtos.isEmpty()) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        } else {
            try {
                List<OrgStructureUser> orgStructureUsers = new ArrayList();
                Iterator iterator = employeeInfoDtos.iterator();
                while(iterator.hasNext()) {
                    EmployeeInfoDto employeeInfoDto = (EmployeeInfoDto)iterator.next();
                    if (employeeInfoDto.getStructureUserId() == null) {
                        return new ResultDTO(ErrorCode.PARAM_MISSING);
                    }

                    OrgStructureUser orgStructureUser = new OrgStructureUser();
                    orgStructureUser.setId(employeeInfoDto.getStructureUserId());
                    orgStructureUsers.add(orgStructureUser);
                }

                this.orgStructureUserService.deleteBatch(orgStructureUsers);
                return new ResultDTO(true);
            } catch (Exception var8) {
                log.error("批量删除退休老师异常", var8);
                return new ResultDTO(false);
            }
        }
    }

    @ApiOperation("查询退休老师分页列表")
    @RequestMapping(value = "getRetiredTeacherInfoPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<EmployeeInfoDto>> getRetiredTeacherInfoPage(
            @ApiParam(value = "接口版本",required = true,defaultValue = "v1") @PathVariable(value = "apiVersion",required = true) String apiVersion,
            @ApiParam(value = "姓名",required = false) @RequestParam(name = "name",required = false) String name,
            @ApiParam(value = "手机号",required = false) @RequestParam(name = "mobile",required = false) String mobile,
            @ApiParam(value = "教工号",required = false) @RequestParam(name = "jobNo",required = false) Long jobNo,
            @ApiParam(value = "组织机构号",required = false) @RequestParam(name = "structureId",required = false) Long structureId,
            @ApiParam(value = "页码",required = false,defaultValue = "1") @RequestParam(name = "pageNo",required = false,defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数",required = false,defaultValue = "10") @RequestParam(name = "pageSize",required = false,defaultValue = "10") Integer pageSize) {
        log.info("***********RetiredTeachersManageController.getRetiredTeacherInfoPage******apiVersion:{},orgId:{},classId:{}", new Object[]{apiVersion, name, mobile});
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else {
            try {
                Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
                Map<String, Object> params = new HashMap(2);
                if (mobile != null) {
                    params.put("mobile", mobile);
                }

                if (name != null) {
                    params.put("name", name);
                }

                if (jobNo != null) {
                    params.put("jobNo", jobNo);
                }

                if (structureId != null) {
                    params.put("structureId", structureId);
                }

                if (orgId != null) {
                    params.put("orgId", orgId);
                }

                return new ResultDTO(this.orgStructureUserService.getRetiredTeachersInfoPageList(params, pageNo, pageSize));
            } catch (Exception e) {
                log.error("***********RetiredTeachersManageController.getRetiredTeacherInfoPage******", e);
                return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
            }
        }
    }

    @ApiOperation("编辑退休老师")
    @RequestMapping(value = "/updateTeacher", method = RequestMethod.PUT)
    public ResultDTO<EmployeeInfoDto> updateTeacher(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @RequestBody EmployeeInfoDto employeeInfoDto) {
        log.info("***********RetiredTeachersManageController.updateTeacher******...apiVersion:{},Employee:{}", apiVersion, employeeInfoDto);
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (employeeInfoDto.getId() != null && employeeInfoDto.getId() != 0L && employeeInfoDto.getUserId() != null && employeeInfoDto.getUserId() != 0L) {
            employeeInfoDto.setMobile((String)null);

            try {
                this.teacherManageService.updateTeacher(employeeInfoDto, userDto.getName());
                return new ResultDTO(true);
            } catch (Exception var5) {
                log.error("***********RetiredTeachersManageController.updateTeacher******", var5);
                return new ResultDTO(false);
            }
        } else {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        }
    }
}
